from rest_framework.viewsets import ModelViewSet
from meiduo_admin.serializers.sku_serializer import *
from goods.models import SKU, GoodsCategory
from meiduo_admin.pages import MyPage
from rest_framework.response import Response
from rest_framework.generics import ListAPIView

class SKUViewSet(ModelViewSet):
    queryset = SKU.objects.all()
    serializer_class = SKUModelSerializer
    pagination_class = MyPage

    def get_queryset(self):

        if self.action == 'categories':
            return GoodsCategory.objects.filter(parent_id__gt=37)

        keyword = self.request.query_params.get('keyword')
        if keyword:
            return self.queryset.filter(name__contains=keyword)
        return self.queryset.all()

    def get_serializer_class(self):
        if self.action == 'categories':
            return GoodsCategoryDetailSerializer
        return self.serializer_class

    def categories(self, request):
        category_3_queryset = self.get_queryset()
        s = self.get_serializer(category_3_queryset, many=True)
        return Response(s.data)

class SPUSimpleView(ListAPIView):
    queryset = SPU.objects.all()
    serializer_class = SPUSimpleSerializer

class SPUSpecSimpleView(ListAPIView):
    queryset = SPUSpecification.objects.all()
    serializer_class = SPUSpecSerializer

    def get_queryset(self):
        spu_id = self.kwargs.get('pk')
        return self.queryset.filter(spu_id=spu_id)